import {getCompany, postCompany, putCompany} from '@/base/api/CompanyApi';
import {AddressItem} from '@/base/Address';
import {isEmpty} from '@/base/util/Strings';
import {CompanyAccountVo} from '@/base/model/CompanyAccountVo';

export class FormBloc {
  form = new CompanyAccountVo();
  addressInfo: Array<AddressItem> = [];
  addressItems: Array<string> = [];

  load(id: number) {
    return getCompany(id)
      .then((res) => {
        let dataItem = res.data;
        this.form.company = dataItem.company;
        this.form.account = dataItem.account;
        // @ts-ignore
        this.form.account.roles = dataItem.account.roles.map(x => (Number(x))) || [];
        this.addressInfo = isEmpty(dataItem.company.city) ? [] : [
          {
            code: dataItem.company.provinceId,
            name: dataItem.company.province
          },
          {
            code: dataItem.company.cityId,
            name: dataItem.company.city
          },
          {
            code: dataItem.company.districtId,
            name: dataItem.company.district
          }
        ];
        this.addressItems = this.addressInfo.map(x => x.code);
        return res;
      });
  }

  save(id: number | '') {
    const entity: any = {
      provinceId: this.addressInfo[0].code,
      province: this.addressInfo[0].name,
      cityId: this.addressInfo[1].code,
      city: this.addressInfo[1].name,
      districtId: this.addressInfo[2].code,
      district: this.addressInfo[2].name,
      address: this.form.company.address,
      clientUrl: this.form.company.clientUrl,
      email: this.form.account.email,
      name: this.form.company.name,
      phone: this.form.account.phone,
      shortName: this.form.company.shortName,
      userName: this.form.account.userName,
      roles: this.form.account.roles
    };
    if (!id) {
      entity.password = this.form.account.password
    }
    return id ? putCompany(id, entity) : postCompany(entity);
  }
}
